﻿using System;
using System.DirectoryServices;
using System.Data.OleDb;
namespace FTchina.Library
{
    /// <summary>
    ///LDAPHelper 的摘要说明
    /// </summary>
    public   class LDAPHelper
    {
        public LDAPHelper()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        protected static string LdapUrl
        {
            get { return "sd.cnc.intra"; }
        }
        /// <summary>
        /// 验证用户名密码是否合法，慢
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool CheckLDAPAccount(string username, string password)
        {

            DirectoryEntry de = new DirectoryEntry("LDAP://" + LdapUrl, username, password, AuthenticationTypes.Secure);
            DirectorySearcher deSearch = new DirectorySearcher();
            deSearch.SearchRoot = de;
            deSearch.Filter = "(&(objectCategory=person)(objectClass=USER))";
            //  deSearch.Filter = "(sAMAccountName=" + username + ")";也可以

            SearchResult results = null;
            try
            {
                results = deSearch.FindOne();
                de.Close();
                de.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.Error("username" + username + "password" + password + ex.Message);
                return false;
            }
            finally
            {
                de.Close();
                de.Dispose();
            }
            return results != null;

        }



       /// <summary>
       /// 验证用户名密码合法性，速度快
       /// </summary>
       /// <param name="username"></param>
       /// <param name="password"></param>
       /// <returns></returns>
        public static Boolean CheckLDAPAccountADODB(string username, string password)
        {

            bool flag = true;
            try
            {
                object parms = Type.Missing;
                object recs = null;
                ADODB.Connection conn = new ADODB.Connection();
                ADODB.Command cmd = new ADODB.Command();
                ADODB.Recordset rs = new ADODB.Recordset();

                conn.Open("Provider=ADsDSOObject", @"sd\"+username, password, 0);

                cmd.ActiveConnection = conn;
                cmd.CommandText = "select cn from 'LDAP://10.72.43.11/OU=东营市分公司,OU=山东省分公司,OU=Chinaunicom-SD,DC=sd,DC=cnc,DC=intra'";

                cmd.Execute(out recs, parms, -1);
                conn.Close();

            }
            catch (SystemException er)
            {
                LogHelper.Error(er.Message);
                flag = false;
            }
            return flag;
        }
    }
}